package com.back.controller;

import com.back.common.utils.Result;
import com.back.common.utils.SecurityUtil;
import com.back.dto.CompanyDTO;
import com.back.dto.CompanyVerificationDTO;
import com.back.entity.Company;
import com.back.service.ICompanyService;
import com.back.service.ICompanyVerificationLogService;
import com.back.vo.CompanyVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  企业前端控制器
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICompanyVerificationLogService verificationLogService;

    /**
     * 获取企业列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN')")
    public Result getCompanyList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String industry,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        Page<Company> page = new Page<>(current, size);
        IPage<CompanyVO> companyList = companyService.getCompanyList(page, industry, status, keyword);
        return Result.ok().data("companyList", companyList);
    }

    /**
     * 获取企业详情
     */
    @GetMapping("/{id}")
    public Result getCompanyDetail(@PathVariable Long id) {
        CompanyVO company = companyService.getCompanyDetail(id);
        return Result.ok().data("company", company);
    }

    /**
     * 创建企业
     */
    @PostMapping
    @PreAuthorize("hasRole('EMPLOYER')")
    public Result createCompany(@RequestBody @Valid CompanyDTO companyDTO) {
        Long userId = SecurityUtil.getCurrentUserId();
        CompanyVO company = companyService.createCompany(companyDTO, userId);
        return Result.ok().data("company", company);
    }

    /**
     * 更新企业信息
     */
    @PutMapping("/{id}")
    public Result updateCompany(@PathVariable Long id, @RequestBody @Valid CompanyDTO companyDTO) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        CompanyVO company = companyService.updateCompany(id, companyDTO);
        return Result.ok().data("company", company);
    }

    /**
     * 删除企业
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('EMPLOYER')")
    public Result deleteCompany(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!SecurityUtil.hasRole("ADMIN") && !companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        boolean success = companyService.deleteCompany(id);
        return success ? Result.ok() : Result.error().message("删除失败");
    }

    /**
     * 上传公司Logo
     */
    @PostMapping("/{id}/logo")
    public Result uploadLogo(@PathVariable Long id, @RequestParam String logoUrl) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        String url = companyService.uploadLogo(id, logoUrl);
        return Result.ok().data("logoUrl", url);
    }

    /**
     * 上传营业执照
     */
    @PostMapping("/{id}/license")
    public Result uploadBusinessLicense(@PathVariable Long id, @RequestParam String licenseUrl) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        String url = companyService.uploadBusinessLicense(id, licenseUrl);
        return Result.ok().data("licenseUrl", url);
    }

    /**
     * 提交企业认证申请
     */
    @PostMapping("/{id}/verification")
    public Result submitVerification(@PathVariable Long id, @RequestBody @Valid CompanyVerificationDTO verificationDTO) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        verificationLogService.submitVerification(id, verificationDTO);
        return Result.ok();
    }

    /**
     * 获取企业认证历史记录
     */
    @GetMapping("/{id}/verification/history")
    public Result getVerificationHistory(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (!SecurityUtil.hasRole("ADMIN") && !companyService.checkCompanyPermission(id, userId)) {
            return Result.error().message("没有操作权限");
        }
        return Result.ok().data("records", verificationLogService.getCompanyVerificationHistory(id));
    }
}
